package com.example.ribbontest.command;

import com.example.ribbontest.domain.User;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import org.springframework.web.client.RestTemplate;

public class UserCommand extends HystrixCommand<User>{
    private RestTemplate restTemplate;
    private int id;

    private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("CommandKey");
    public UserCommand(Setter setter,RestTemplate restTemplate)
    {
        super(setter);
        this.restTemplate = restTemplate;
    }

    public UserCommand(Setter setter,RestTemplate restTemplate,int id)
    {
        super(setter);
        this.restTemplate = restTemplate;
        this.id = id;
    }
    @Override
    protected User run()
    {
        return restTemplate.getForObject("http://SPRING-BOOT-TEST/user/{1}",User.class,id);
    }

    @Override
    protected User getFallback() {
        return new User("fallbackUser","forbackpassword");
    }

    @Override
    protected String getCacheKey()
    {
        return String.valueOf(id);
    }

    /**
     * 清空缓存方法
     * @param id
     */
    public static void flushCache(int id)
    {
        HystrixRequestCache.getInstance(GETTER_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(String.valueOf(id));
    }

}
